/**
 * 
 */
package cn.springsoter.core.tool.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

/**
 * 字符串工具类
 * @author kevin
 *
 */
public class StringUtil extends cn.hutool.core.util.StrUtil {
	private StringUtil() {}
	
	/**
	 * Gets the absolute path.
	 *
	 * @return the absolute path
	 * @Title: getAbsolutePath
	 * @Description: 获取webRoot的根目录
	 */
	public static String getAbsolutePath() {
		String path = Thread.currentThread().getContextClassLoader()
				.getResource("").toString();
		path = path.replaceAll("\\\\", "/");
		if (path.startsWith("file:")) {
			path = path.replaceFirst("file:", "");
		}
		if (path.endsWith("/WEB-INF/classes/")) {
			path = path.replaceAll("/WEB-INF/classes/", "");
		}
		return path;
	}

	/**
	 * Gets the extension name.
	 *
	 * @param filename
	 *            the filename
	 * @return the extension name
	 * @Title: getExtensionName
	 * @Description: 获取文件扩展名，比如：aaa.jpg-->jpg
	 */
	public static String getExtensionName(String fullName) {
		Assert.notNull(fullName, "file fullName is null.");
		String fileName = new File(fullName).getName();
		int dotIndex = fileName.lastIndexOf('.');
		return (dotIndex == -1) ? StringUtils.EMPTY : fileName.substring(dotIndex + 1);
	}
	
	/**
	 * MD5加密.
	 *
	 * @param str
	 *            the str
	 * @return the string
	 */
	public static String md5Encode(String str) {
		StringBuffer buf = new StringBuffer();
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes());
			byte bytes[] = md5.digest();
			for (int i = 0; i < bytes.length; i++) {
				String s = Integer.toHexString(bytes[i] & 0xff);// 将byte转换成int，然后再转成16进制string
				if (s.length() == 1) {
					buf.append("0");
				}
				buf.append(s);
			}

		} catch (Exception ex) {
		}
		return buf.toString();
	}
	
	/**
	 * 清除查询条件里的%和_.
	 *
	 * @param keyword
	 *            the keyword
	 * @return the string
	 */
	public static String transfer(String keyword) {
		if (StringUtils.isNotBlank(keyword)) {
			if (keyword.contains("%") || keyword.contains("_")) {
				keyword = keyword.replaceAll("\\\\", "\\\\\\\\")
						.replaceAll("\\%", "\\\\%").replaceAll("\\_", "\\\\_");
			}
		}
		return keyword;
	}

	/**
	 * 替换字符串里的\r\n\t .
	 *
	 * @param str
	 *            the str
	 * @return String 返回类型
	 * @Title: replaceBlank
	 * @Description: 替换字符串里的\r\n\t
	 */
	public static String replaceBlank(String str) {
		String dest = str;
		if (str != null) {
			Pattern p = Pattern.compile("\\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	
	/**
	 * Encode str.
	 *
	 * @param str
	 *            the str
	 * @return the string
	 * @Title: encodeStr
	 * @Description: 把中文编码ISO-8859-1转换成utf-8编码
	 */
	public static String encodeStr(String str) {
		try {
			return StringUtils.isBlank(str) ? null : new String(
					str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	

	/**
	 * Gets the random string.
	 *
	 * @param length
	 *            the length
	 * @return the random string2
	 * @Title: getRandomString2
	 * @Description: 获取一个随机字符串，包含字母和数字
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sf = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(3);
			long result = 0;

			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);// A-Z
				sf.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);// a-z
				sf.append(String.valueOf((char) result));
				break;
			case 2:
				sf.append(String.valueOf(new Random().nextInt(10)));// 0-9
				break;
			}
		}

		return sf.toString();
	}
	
	/**
	 * 创建StringBuilder对象
	 *
	 * @param sb   初始StringBuilder
	 * @param strs 初始字符串列表
	 * @return StringBuilder对象
	 */
	public static StringBuilder appendBuilder(StringBuilder sb, CharSequence... strs) {
		for (CharSequence str : strs) {
			sb.append(str);
		}
		return sb;
	}
	
	/**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }
    
	/**
	 * 生成uuid，作废，请改为：StringUtil.uuid();
	 *
	 * @return UUID
	 */
	@Deprecated
	public static String randomUUID() {
		ThreadLocalRandom random = ThreadLocalRandom.current();
		return new UUID(random.nextLong(), random.nextLong()).toString().replace(StringPool.DASH, StringPool.EMPTY);
	}
}
